package com.echo.code.thread.future.service.impl;

import com.echo.code.thread.future.Future;
import com.echo.code.thread.future.impl.SimpleFuture;
import com.echo.code.thread.future.service.FutureService;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * FutureServiceImpl Created by baiyap on 2018/9/24.
 */
public class FutureServiceImpl<I, O> implements FutureService<I, O> {

  @Override
  public Future<?> submit(Runnable runnable) {
    Objects.requireNonNull(runnable);
    final Future<Void> future = new SimpleFuture<>();
    new Thread(() -> {
      runnable.run();
      future.finish(null);
    }).start();
    return future;
  }

  @Override
  public Future<O> submit(Function<I, O> function, I input) {
    Objects.requireNonNull(function);
    final Future<O> future = new SimpleFuture<>();
    new Thread(() -> {
      O result = function.apply(input);
      future.finish(result);
    }).start();
    return future;
  }

  @Override
  public Future<O> submit(Function<I, O> function, I input, Consumer<O> callback) {
    Objects.requireNonNull(function);
    Objects.requireNonNull(callback);
    final Future<O> future = new SimpleFuture<>();
    new Thread(() -> {
      O result = function.apply(input);
      future.finish(result);
      callback.accept(result);
    }).start();
    return future;
  }
}